package cn.xmkeshe.back.impl;

import cn.xmkeshe.back.IAdminServiceBack;
import cn.xmkeshe.dao.IActionDao;
import cn.xmkeshe.dao.IAdminDao;
import cn.xmkeshe.dao.IRoleDao;
import cn.xmkeshe.model.Admin;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class IAdminServiceBackImpl implements IAdminServiceBack {

  @Resource
  private IAdminDao iAdminDao;
  @Resource
  private IActionDao iActionDao;
  @Resource
  private IRoleDao iRoleDao;

  @Override
  @Transactional(propagation = Propagation.REQUIRED)
  public Admin get(String aid) {
    Admin admin = iAdminDao.findById(aid);
    if (admin != null) {
      Date date = new Date();
      if (iAdminDao.doUpdateByLastdate(aid,date)) {
        return admin;
      }
    }
    return null;
//    return iAdminDao.findById(aid);
  }

  @Override
  @Transactional(readOnly = true)
  public Map<String, Object> listAuthByAdmin(String aid) {
    HashMap<String, Object> map = new HashMap<>();
    map.put("allRoles",this.iRoleDao.findAllRoleByAdmin(aid));
    map.put("allActions",this.iActionDao.findAllActionByAdmin(aid));
    return map;
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED)
  public boolean insert(Admin admin, Set<Integer> rid) {

    if (iAdminDao.findById(admin.getAid())==null){
      if (iAdminDao.doCreate(admin)){
        Iterator<Integer> iter = rid.iterator();
        while (iter.hasNext()){
          Map<String,Object> map = new HashMap<String, Object>();
          map.put("aid",admin.getAid());
          map.put("rid",iter.next());
          iAdminDao.doCreateAdminByRole(map);
        }
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean updateByPassword(String aid, String password) {
    return iAdminDao.doUpdateByPassword(aid,password);
  }


  @Override
  @Transactional(readOnly = true)
  public Map<String, Object> listSplit(int currentPage, int lineSize) {
    Map<String,Object> result = new HashMap<String, Object>();
    result.put("start",(currentPage-1)*lineSize);
    result.put("lineSize",lineSize);
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("allAdmin",iAdminDao.findAllSplit(result));
    map.put("allCount",iAdminDao.getAllCount());
    System.out.println(map);
    return map;
  }

  @Override
  @Transactional(readOnly = true)
  public Map<String, Object> findByName(int currentPage, int lineSize, String name) {
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("data",iAdminDao.findByName((currentPage-1)*lineSize, lineSize,name));
    map.put("count",iAdminDao.getAllCount());
    return map;
  }
}
